package groep1.filter;

import groep1.ObjectList;
import groep1.ObjectRepresentation;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import bluej.debugger.DebuggerField;
import bluej.debugmgr.inspector.FieldInfo;
import bluej.debugmgr.inspector.Inspector;

public class StartFilter extends FilterHierarchyObject {
	
	private FilterHierarchyObject filter;
	
	/**
	 * Create a new
	 * 
	 * @param	regex
	 * 			| The regular expression this filter must apply.
	 * @param objects 
	 */
	public StartFilter(String regex, HashSet<ObjectRepresentation> objects) {
		filter = parseRegex(regex, objects);
	}

	@Override
	public HashMap<String, List<FieldInfo>> join() {
		return checkDependencies(filter.join());
	}
	
	public FilterHierarchyObject getFilter(){
		return filter;
	}
	
	private HashMap<String, List<FieldInfo>> checkDependencies(HashMap<String, List<FieldInfo>> filteredObjects) {
		boolean remove;
		do {
			remove = false;
			for(ObjectRepresentation currentObject : ObjectList.getInstance().getObjectRepresentations()){
				HashMap<ObjectRepresentation,List<DebuggerField>> references = currentObject.getReferences();
				boolean objectStillExist;
				if(references.isEmpty())
					objectStillExist = true;
				else
					objectStillExist = false;
				for(ObjectRepresentation objectHead: references.keySet()){
					try {
						if(filteredObjects.containsKey(objectHead.getUniqueKey())){
							List<DebuggerField> fields = references.get(objectHead);
							List<FieldInfo> fieldsHead = filteredObjects.get(objectHead.getUniqueKey());
							for(DebuggerField field: fields){
								for(FieldInfo info: fieldsHead){
									if(info.getDescription().equals(Inspector.fieldToString(field))){
										objectStillExist = true;
									}
								}
							}
						}
					} catch (NullPointerException e) {
							objectStillExist = false;
							break;
					}
				}
				if(!objectStillExist && filteredObjects.containsKey(currentObject.getUniqueKey())){
					filteredObjects.remove(currentObject.getUniqueKey());
					remove = true;
				}
			}
		} while(remove);
		return filteredObjects;
	}
}
